<?php

/*-----------------------------------------------------------------------------------*/
/* Start WooThemes Functions - Please refrain from editing this section */
/*-----------------------------------------------------------------------------------*/

// Define the theme-specific key to be sent to PressTrends.
define( 'WOO_PRESSTRENDS_THEMEKEY', 'pivqh37o1az912ycxt502jsfg2vcbtam7' );

// WooFramework init
require_once ( get_template_directory() . '/functions/admin-init.php' );	

/*-----------------------------------------------------------------------------------*/
/* Load the theme-specific files, with support for overriding via a child theme.
/*-----------------------------------------------------------------------------------*/

$includes = array(
				'includes/theme-options.php', 			// Options panel settings and custom settings
				'includes/theme-functions.php', 		// Custom theme functions
				'includes/theme-actions.php', 			// Theme actions & user defined hooks
				'includes/theme-comments.php', 			// Custom comments/pingback loop
				'includes/theme-js.php', 				// Load JavaScript via wp_enqueue_script
				'includes/sidebar-init.php', 			// Initialize widgetized areas
				'includes/theme-widgets.php'			// Theme widgets
				);

// Allow child themes/plugins to add widgets to be loaded.
$includes = apply_filters( 'woo_includes', $includes );
				
foreach ( $includes as $i ) {
	locate_template( $i, true );
}

// Load WooCommerce functions, if applicable.
if ( is_woocommerce_activated() ) {
	locate_template( 'includes/theme-woocommerce.php', true );
}

/*-----------------------------------------------------------------------------------*/
/* You can add custom functions below */
/*-----------------------------------------------------------------------------------*/

function removeCommas ( $str ) {
	$str = str_replace(',', ' ', $str);
	return $str;
}  //removeCommas()

function removeHyphens ( $str ) {
	return str_replace('-', '', $str);
}

function create_and_export_CSV_order_file($orderId) {
	


	
	//Step 1: import woocommerce classes and define variables and functions
	global $woocommerce;
		
	$fileName = 'Order-' . $orderId . '.csv';
	$filePath = '/home/sacredmusic/webapps/illuminare_wp/wp-content/themes/merchant/orderCSVs/' . $fileName;
	
	$siteAdminEmail = get_bloginfo('admin_email');
	$developerEmail = $siteAdminEmail . ", " . "bbloomfield@illuminarepublications.com";  //used for status updates
	$emergencyEmail = $siteAdminEmail . ", " . "bbloomfield@illuminarepublications.com"; //used for error reporting
	$errorFlag = false;
	$errorMsgTitle = "Illuminare Publications Order #" . $orderId . " - An error has occurred in the automated order .CSV export process";
	$errorMsgContent = "";
	$errorEmailHeader = 'From: Illuminare Publications <do_not_reply@illuminarepublications.com>' . "\r\n".'MIME-Version: 1.0' . "\r\n".'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	
	//the $list array will eventually be used to populate the .CSV file
	$list = array (
		array('Order Number', 
			  'Item', 
			  'Quantity', 
			  'Order Date', 
			  'Ship Date', 
			  'Ship to Name', 
			  'Ship to Address 1', 
			  'Ship to Address 2', 
			  'Ship to Address 3', 
			  'Ship to City', 
			  'Ship to State', 
			  'Ship to Zip', 
			  'Ship to Country', 
			  'Bill to Name', 
			  'Bill to Address 1', 
			  'Bill to Address 2', 
			  'Bill to Address 3', 
			  'Bill to City', 
			  'Bill to State', 
			  'Bill to Zip', 
			  'Bill to Country', 
			  'Carrier', 
			  'Service', 
			  'International', 
			  'Rate Type', 
			  'Customer Purchase Order', 
			  'Customer E-Mail Address', 
			  'Comment Line 1', 
			  'Comments Line 2', 
			  'Comments Line 3', 
			  'Comments Line 4', 
			  'Comments Line 5', 
			  'Ship to Country Code', 
			  'Bill to Country Code', 
			  'Saturday Del', 
			  'DCR', 
			  'Signature', 
			  'Ins', 
			  'Ins Amt', 
			  'pay_type', 
			  'Pay type Account')
		); //end of $list creation
	
	//Step 2: retrieve order
	$order = new WC_Order($orderId);
	
	//Step 3: retrieve order items
	$items = $order->get_items();
	
	//Step 4: for each item on the order, add a line to the $list array.
	foreach($items as $item) {
		$product = $order->get_product_from_item( $item );
    if(removeCommas(removeHyphens($product->get_attribute('ISBN')))==''){
      continue;
    }
		//$mj_order->add_item( $item['name'], $wc_order->get_item_subtotal($item), $item['qty'], $product->get_sku() );
		/*if ( $item['qty'] > 499 ) {
			$carrierCode = 'TRU';
			$serviceCode = 'CKPR';
			$comments = 'Please ship ABF.';
		} else if ( $item['qty'] > 6 && $item['qty'] <= 499 ) {
			$carrierCode = 'FDX';
			$serviceCode = 'PRE';
			$comments = '';
		} else {
			$carrierCode = 'SPS';
			$serviceCode = 'MED';
			$comments = '';
		}*/
		
		$shipping_method = $order->shipping_method;
    $shipping_account = $order->order_custom_fields['shipping_account'];
    if($shipping_account && is_array($shipping_account)) {
      $shipping_account = $shipping_account[0];
    }
    if($shipping_account && strlen($shipping_account) != 0) {
      $serviceCode = '3PB';
    }
		
		//extract carrier and service from the woocommerce shipping method
    $colonPos = strpos( $shipping_method, ':' );
    if($colonPos === false) {
      $carrier = $shipping_method;
    } else {
  		$carrier = substr( $shipping_method, 0, $colonPos );
  		$service = substr( $shipping_method, $colonPos + 1 );
		}
    
		//set Ware-Pak accepted values for carrier and service codes
		switch ( strtoupper( $carrier ) ) {
			
			case 'FEDEX':
				
				$carrierCode = 'FDX';
				if(!$serviceCode) {
  				switch ( strtoupper( $service ) ) {
  					
  					/*case 'FIRST_OVERNIGHT':
  						$serviceCode = 'NDE';
  						break;
  					case 'PRIORITY_OVERNIGHT':
  						$serviceCode = 'ND';
  						break;
  					case 'STANDARD_OVERNIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_2_DAY_AM':
  						$serviceCode = '';
  						break;*/
  					case 'FEDEX_2_DAY':
  						$serviceCode = '2D';
  						break;
  					case 'FEDEX_EXPRESS_SAVER':
  						$serviceCode = '3D';
  						break;
  					/*case 'GROUND_HOME_DELIVERY':
  						$serviceCode = '';
  						break;*/
  					case 'FEDEX_GROUND':
  						$serviceCode = 'PRE';
  						break;
  					case 'INTERNATIONAL_ECONOMY':
  						$serviceCode = 'IEC';
  						break;
  					/*case 'INTERNATIONAL_FIRST':
  						$serviceCode = '';
  						break;*/
  					case 'INTERNATIONAL_PRIORITY':
  						$serviceCode = 'IPR';
  						break;
  					/*case 'EUROPE_FIRST_INTERNTIONAL_PRIORITY':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_1_DAY_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_2_DAY_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_3_DAY_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'INTERNATIONAL_ECONOMY_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'INTERNATIONAL_PRIORITY_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_NATIONAL_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'INTERNATIONAL_GROUND':
  						$serviceCode = '';
  						break;
  					case 'SMART_POST':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_FIRST_FREIGHT':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_FREIGHT_ECONOMY':
  						$serviceCode = '';
  						break;
  					case 'FEDEX_FREIGHT_PRIORITY':
  						$serviceCode = '';
  						break;*/
  					default:
  						$serviceCode = '3D'; //default to fedex express saver
  				}
				}
				break;
				
			case 'UPS':
				
				$carrierCode = 'UPS';
				if(!$serviceCode) {
  				switch ( strtoupper( $service ) ) {
  					
  					case '12':
  						$serviceCode = '3D';
  						break;
  					case '03':
  						$serviceCode = 'GD';
  						break;
  					/*case '02':
  						$serviceCode = '2D';
  						break;
  					case '59':
  						$serviceCode = '2DC';
  						break;
  					case '01':
  						$serviceCode = 'ND';
  						break;
  					case '13':
  						$serviceCode = '1P';
  						break;
  					case '14':
  						$serviceCode = 'EAM';
  						break;
  					case '11':
  						$serviceCode = '';
  						break;*/
  					case '07':
  						$serviceCode = 'EXP';
  						break;
  					/*case '54':
  						$serviceCode = 'PLUS';
  						break;*/
  					case '08':
  						$serviceCode = 'EX';
  						break;
  					/*case '65':
  						$serviceCode = '';
  						break;*/
  					default:
  						$serviceCode = 'GD';
  				}
        }
				
				break;
				
			case 'USPS':
				
				$carrierCode = 'SPS';
				
				switch ( strtoupper( $service ) ) {

					case 'D0':
						$serviceCode = 'FIR';
						break;
					case 'D1':
						$serviceCode = 'PRI';
						break;
					case 'D6':
						$serviceCode = 'MED';
						break;
          case 'I2': // Priority International
            $serviceCode = 'PMI';
            break;
					case 'I15': // First Class International
            $serviceCode = 'FMI'
            break;
          default:
						$serviceCode = 'MED';
				}
				
				break;
				
			case 'TABLE_RATE':
      case 'ABF':
      case 'ABF FREIGHT':
			
				$carrierCode = 'TRU';
				$serviceCode = 'CKPR';
				$comments = 'Please ship ABF.';
				
				break;
				
			case 'FREE_SHIPPING':
			
				if ( $item['qty'] > 499 ) {
					$carrierCode = 'TRU';
					$serviceCode = 'CKPR';
					$comments = 'Please ship ABF.';
				} else if ( $item['qty'] > 6 && $item['qty'] <= 499 ) {
					$carrierCode = 'FDX';
					$serviceCode = 'PRE';
					$comments = '';
				} else {
					$carrierCode = 'SPS';
					$serviceCode = 'MED';
					$comments = '';
				}
				
				break;
		}
    if($serviceCode == '3PB') {
      $comments = $shipping_account;
    }
    if(!$carrierCode || !$serviceCode) {
      $errorMsgContent = "No carrier code/service code determined for order numer $orderId.
The shipping method stored in the order object was '" .
        $order->shipping_method . "'
The carrier stripped from this was '$carrier' and the service '$service'.
The carrier code determined from these was '$carrierCode' with service code '$serviceCode'.
Entire order object follows.

" . print_r($order,true);
      mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
    }
		$list[] = array($orderId, 
						removeCommas(removeHyphens($product->get_attribute('ISBN'))), 
						$item['qty'], 
						$order->order_date, 
						date("Y-m-d"), 
						removeCommas($order->shipping_first_name . ' ' . $order->shipping_last_name), 
						removeCommas($order->shipping_address_1), 
						removeCommas($order->shipping_address_2), 
						' ',
						removeCommas($order->shipping_city), 
						removeCommas($order->shipping_state), 
						removeCommas($order->shipping_postcode), 
						removeCommas($order->shipping_country),
						removeCommas($order->billing_first_name . ' ' . $order->billing_last_name), 
						removeCommas($order->billing_address_1), 
						removeCommas($order->billing_address_2), 
						' ',
						removeCommas($order->billing_city), 
						removeCommas($order->billing_state), 
						removeCommas($order->billing_postcode), 
						removeCommas($order->billing_country),
						removeCommas($carrierCode),  //postal
						removeCommas($serviceCode),  //USPS Media Mail
						'N',
						'R', //rate type
						'', //'Customer Purchase Order', 
						removeCommas($order->billing_email), //'Customer E-Mail Address', 
						$comments, //removeCommas(substr($order->customer_note, 0, 50)), //'Comment Line 1', 
						'',//removeCommas(substr($order->customer_note, 49, 50)), //'Comments Line 2', 
						'',//removeCommas(substr($order->customer_note, 99, 50)), //'Comments Line 3', 
						'',//removeCommas(substr($order->customer_note, 149, 50)), //'Comments Line 4', 
						'',//removeCommas(substr($order->customer_note, 199, 50)), //'Comments Line 5', 
						'', //'Ship to Country Code', 
						'', //'Bill to Country Code', 
						'', //'Saturday Del', 
						'', //'DCR', 
						'', //'Signature', 
						'', //'Ins', 
						'', //'Ins Amt', 
						'', //'pay_type', 
						'' //'Pay type Account'
						);
	}  //end of item loop
	
	
	//mail('bbloomfield@illuminarepublications.com', 'inside create_and_export_CSV_order_file', 'shipping_method: ' . $order->shipping_method . '<br />shipping_method_title: ' . $order->shipping_method_title . '<br />$carrier: ' . $carrier . '<br />$service: ' . $service, $errorEmailHeader);
	
	
	//Step 5: create CSV file from $list array
	
	error_reporting(E_ALL);
	
	$fp = fopen($filePath, 'w');
	
	if (!$fp) {
		$errorMsgContent .= "Error: Attempted to create file: " . $filePath . "...<br />";
		$errorArray = error_get_last();
		$errorMsgContent .= "errorArray[file] = " . $errorArray['file'] . " errorArray[type] = " . $errorArray['type'] . " errorArray[message] = " . $errorArray['message'] . " errorArray[line] = " . $errorArray['line'];
		mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
	}

	foreach ($list as $fields) {
		if (!fputcsv($fp, $fields)){
			$errorMsgContent .= "Error: Attempted to write a line to this file: " . $filePath . "...<br />";
			mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
		}
	}
	
	fclose($fp);
	
	//Step 6: connect to Ware-Pak FTP server and upload file.  If errors occur, generate emails to notify Adam and Steve
	
	//ftp logic
	$ftp_server = get_option('ip_export_ftp_host');
	$ftp_user_name = get_option('ip_export_ftp_user');
	$ftp_user_pass = get_option('ip_export_ftp_pwd');
	
	//make FTP connection
	$conn_id=ftp_connect($ftp_server);
	
	// login with username and password
	
	if ( ! $conn_id ) {
		$errorMsgContent .= "Attempted to connect to " . $ftp_server . "<br />";
		$errorMsgContent .= "Connection attempt failed.<br />";
		//send notification message and exit
		mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
		exit;
	} else {
		$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
	}
	
	
	// check connection
	if ( ! $login_result ) {
       $errorMsgContent .= "Attempted to login to " . $ftp_server . " for user " . $ftp_user_name . "....<br />";
       $errorMsgContent .= "Connection attempt failed.<br />";
	   //send notification message and exit
	   mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
       exit;
	} else {
       //echo "Connected to $ftp_server, for user $ftp_user_name".".....";
	}
	
	// upload the file
	$upload = ftp_put($conn_id, '/incoming/' . $fileName, $filePath, FTP_ASCII);
 
	// check upload status
	if (!$upload) {
		$errorMsgContent .= "FTP upload has failed!";
		mail($emergencyEmail, $errorMsgTitle, $errorMsgContent, $errorEmailHeader);
	} else {
		
		mail($developerEmail, "Uploaded " . $fileName . " to " . $ftp_server, '', $errorEmailHeader);
	}
	
	ftp_close($conn_id);
	
}
add_action('woocommerce_order_status_processing', 'create_and_export_CSV_order_file', 10, 1);

add_action('admin_menu', 'ip_csv_export_administration');

function ip_csv_export_administration() {
	add_submenu_page('woocommerce', 'Custom CSV Export', 'Custom CSV Export', 'manage_options', 'ip_csv_export', 'ip_csv_export');
}

function ip_csv_export() {
	
	if (!current_user_can('manage_options'))  {
		wp_die( __('You do not have sufficient permissions to access this page.') );
	}
	
	$baseUrl = get_bloginfo('wpurl');
	
	//check for presence of hidden parameter and for the correct value
	if (isset($_POST['posted']) && 'true' === ($_POST['posted'])) {
		
		update_option ( 'ip_export_ftp_host', $_POST[ 'ftp_host' ]);
		update_option ( 'ip_export_ftp_user', $_POST[ 'ftp_user' ]);
		update_option ( 'ip_export_ftp_pwd', $_POST[ 'ftp_pwd' ]);
		
		$statusMessage = 'Update saved successfully!';
		
		if (isset($_POST['backlogUpdate']) && 'Run' === ($_POST['backlogUpdate'])) {
			create_CSV_files_for_order_backlog();
		}
		
	}
?>
	<h1>Illuminare Publications - Custom Order CSV Export</h1>
	
	<h3><?php echo $statusMessage; ?></h3>
	
	<form name="ampQuestions" id="ampQuestions" action="" method="post">
		<input type="hidden" name="posted" id="posted" value="true" />
		<table>
			<tr>
				<td>FTP Host:</td>
				<td><input type="text" name="ftp_host" id="ftp_host" value="<?php echo get_option('ip_export_ftp_host'); ?>" size="30" /></td>
			</tr>		
			<tr>
				<td>FTP User:</td>
				<td><input type="text" name="ftp_user" id="ftp_user" value="<?php echo get_option('ip_export_ftp_user'); ?>" size="30" /></td>
			</tr>		
			<tr>
				<td>FTP Password:</td>
				<td><input type="text" name="ftp_pwd" id="ftp_pwd" value="<?php echo get_option('ip_export_ftp_pwd'); ?>" size="30" /></td>
			</tr>
			<!--<tr>
				<td>Backlog Update</td>
				<td><input type="text" name="backlogUpdate" id="backlogUpdate" /></td>
			</tr>-->
			<tr>
				<td><input type="submit" value="save" /></td>
				<td>&nbsp;</td>
			</tr>
		</table>
		
	</form>
	
<?php
}







/*-----------------------------------------------------------------------------------*/
/* Don't add any code below here or the sky will fall down */
/*-----------------------------------------------------------------------------------*/
?>
